package org.example.versii.register.impl;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.example.versii.register.IRegistry;
import org.example.versii.util.ZPathUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @author mojito
 * @Classname AbstractRegister
 * @Description TODO
 * @Date 2020/8/3 下午11:47
 **/
@Component("simpleRegister")
public class SimpleRegister implements IRegistry {

    protected CuratorFramework curator;
    @Value("${rpc.server.registry.namespace}")
    private String namespace;
    @Value("${rpc.server.registry.address}")
    private String address;

    @PostConstruct
    public void init() {
        curator = CuratorFrameworkFactory.builder()
                .connectString(address)
                .sessionTimeoutMs(15000)
                .retryPolicy(new ExponentialBackoffRetry(1000, 3))
                .namespace(namespace)
                .build();
        curator.start();
    }

    @Override
    public void registry(String serviceName, String addr) {
        String path = ZPathUtils.getPath(serviceName, addr);
        try {
            curator.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL)
                    .forPath(path);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
